const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')
const http = require('http')
const isDev = process.env.NODE_ENV === 'development'

let mainWindow

// 等待服务器就绪的函数
function waitForServer(url, timeout = 30000) {
  return new Promise((resolve, reject) => {
    const startTime = Date.now()
    let isResolved = false
    
    const checkServer = () => {
      if (isResolved) return
      
      const urlObj = new URL(url)
      const options = {
        hostname: urlObj.hostname,
        port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
        path: urlObj.pathname || '/',
        method: 'GET',
        timeout: 2000
      }

      const req = http.request(options, (res) => {
        if (isResolved) return
        if (res.statusCode === 200 || res.statusCode === 304 || res.statusCode === 404) {
          // 404 也算服务器已启动（Vue Router 可能返回 404）
          isResolved = true
          resolve()
        } else {
          if (Date.now() - startTime < timeout) {
            setTimeout(checkServer, 1000)
          } else {
            isResolved = true
            reject(new Error('服务器响应超时'))
          }
        }
      })

      req.on('error', (err) => {
        if (isResolved) return
        const elapsed = Date.now() - startTime
        if (elapsed < timeout) {
          // 继续等待
          setTimeout(checkServer, 1000)
        } else {
          isResolved = true
          reject(new Error('无法连接到服务器，请确保开发服务器已启动'))
        }
      })

      req.on('timeout', () => {
        req.destroy()
        if (isResolved) return
        const elapsed = Date.now() - startTime
        if (elapsed < timeout) {
          setTimeout(checkServer, 1000)
        } else {
          isResolved = true
          reject(new Error('连接超时'))
        }
      })

      try {
        req.end()
      } catch (err) {
        if (!isResolved) {
          const elapsed = Date.now() - startTime
          if (elapsed < timeout) {
            setTimeout(checkServer, 1000)
          } else {
            isResolved = true
            reject(err)
          }
        }
      }
    }

    checkServer()
  })
}

function createWindow() {
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 1000,
    minHeight: 600,
    webPreferences: {
      // 启用 Node.js 集成（如果需要）
      nodeIntegration: false,
      // 启用上下文隔离
      contextIsolation: true,
      // 预加载脚本
      preload: path.join(__dirname, 'preload.js'),
      // 禁用 webSecurity（如果需要访问本地文件或跨域）
      webSecurity: !isDev
    },
    // 窗口图标（如果存在）
    // icon: path.join(__dirname, '../build/icon.png'),
    // 显示窗口前准备就绪
    show: false,
    // 窗口标题栏样式
    titleBarStyle: 'default'
  })

  // 窗口准备好后显示
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
    
    // 开发环境下打开开发者工具
    if (isDev) {
      mainWindow.webContents.openDevTools()
    }
  })

  // 加载应用
  if (isDev) {
    // 开发环境：先显示等待页面，然后尝试连接服务器
    showWaitingPage()
    
    // 等待开发服务器就绪后加载
    waitForServer('http://localhost:8080', 30000)
      .then(() => {
        mainWindow.loadURL('http://localhost:8080')
      })
      .catch((error) => {
        showErrorPage(error.message)
      })
  } else {
    // 生产环境：加载打包后的文件
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  }
  
  // 显示等待页面
  function showWaitingPage() {
    mainWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(`
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="utf-8">
          <title>等待开发服务器...</title>
          <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { 
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; 
              display: flex; 
              justify-content: center; 
              align-items: center; 
              height: 100vh; 
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              color: white;
            }
            .container {
              text-align: center;
              padding: 60px 40px;
              background: rgba(255,255,255,0.1);
              border-radius: 16px;
              backdrop-filter: blur(10px);
              box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            }
            .spinner {
              border: 4px solid rgba(255,255,255,0.3);
              border-top: 4px solid white;
              border-radius: 50%;
              width: 50px;
              height: 50px;
              animation: spin 1s linear infinite;
              margin: 0 auto 20px;
            }
            @keyframes spin {
              0% { transform: rotate(0deg); }
              100% { transform: rotate(360deg); }
            }
            h1 { font-size: 24px; margin-bottom: 10px; }
            p { font-size: 14px; opacity: 0.9; }
          </style>
        </head>
        <body>
          <div class="container">
            <div class="spinner"></div>
            <h1>正在连接开发服务器...</h1>
            <p>请确保已运行: <code style="background: rgba(0,0,0,0.2); padding: 2px 8px; border-radius: 4px;">npm run serve</code></p>
          </div>
        </body>
      </html>
    `)}`)
  }
  
  // 显示错误页面
  function showErrorPage(errorMsg) {
    mainWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(`
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="utf-8">
          <title>连接失败</title>
          <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { 
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; 
              display: flex; 
              justify-content: center; 
              align-items: center; 
              height: 100vh; 
              background: #f5f5f5;
            }
            .container {
              text-align: center;
              padding: 50px 40px;
              background: white;
              border-radius: 12px;
              box-shadow: 0 4px 20px rgba(0,0,0,0.1);
              max-width: 500px;
            }
            .icon { font-size: 64px; margin-bottom: 20px; }
            h1 { color: #e74c3c; font-size: 24px; margin-bottom: 15px; }
            p { color: #666; line-height: 1.8; margin-bottom: 10px; }
            code { 
              background: #f4f4f4; 
              padding: 4px 12px; 
              border-radius: 6px;
              font-family: 'Courier New', monospace;
              color: #e74c3c;
              font-size: 14px;
            }
            .retry {
              margin-top: 30px;
              padding: 12px 24px;
              background: #667eea;
              color: white;
              border: none;
              border-radius: 6px;
              cursor: pointer;
              font-size: 14px;
              transition: background 0.3s;
            }
            .retry:hover { background: #5568d3; }
            .auto-retry {
              margin-top: 15px;
              color: #999;
              font-size: 12px;
            }
          </style>
        </head>
        <body>
          <div class="container">
            <div class="icon">⚠️</div>
            <h1>无法连接到开发服务器</h1>
            <p>请确保 Vue 开发服务器正在运行：</p>
            <p><code>npm run serve</code></p>
            <p style="margin-top: 20px; color: #999; font-size: 13px;">
              ${errorMsg || '连接超时'}
            </p>
            <button class="retry" onclick="location.reload()">重试连接</button>
            <p class="auto-retry">每 3 秒自动重试...</p>
          </div>
          <script>
            // 每3秒尝试重新连接
            let retryCount = 0
            const maxRetries = 100 // 最多重试100次（5分钟）
            const retryInterval = setInterval(() => {
              retryCount++
              if (retryCount > maxRetries) {
                clearInterval(retryInterval)
                document.querySelector('.auto-retry').textContent = '已达到最大重试次数，请手动刷新'
                return
              }
              fetch('http://localhost:8080')
                .then(() => {
                  clearInterval(retryInterval)
                  location.reload()
                })
                .catch(() => {
                  // 继续等待
                })
            }, 3000)
          </script>
        </body>
      </html>
    `)}`)
  }

  // 窗口关闭事件
  mainWindow.on('closed', () => {
    mainWindow = null
  })

  // 处理外部链接
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    require('electron').shell.openExternal(url)
    return { action: 'deny' }
  })
}

// 应用准备就绪
app.whenReady().then(() => {
  createWindow()

  // macOS 特殊处理：点击 dock 图标时重新创建窗口
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })

  // 创建应用菜单（可选）
  createMenu()
})

// 所有窗口关闭时退出应用（Windows 和 Linux）
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 创建应用菜单
function createMenu() {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
          click: () => {
            app.quit()
          }
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
        { label: '重做', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
        { type: 'separator' },
        { label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
        { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
        { label: '全选', accelerator: 'CmdOrCtrl+A', role: 'selectAll' }
      ]
    },
    {
      label: '视图',
      submenu: [
        { label: '重新加载', accelerator: 'CmdOrCtrl+R', role: 'reload' },
        { label: '强制重新加载', accelerator: 'CmdOrCtrl+Shift+R', role: 'forceReload' },
        { label: '切换开发者工具', accelerator: 'F12', role: 'toggleDevTools' },
        { type: 'separator' },
        { label: '实际大小', accelerator: 'CmdOrCtrl+0', role: 'resetZoom' },
        { label: '放大', accelerator: 'CmdOrCtrl+Plus', role: 'zoomIn' },
        { label: '缩小', accelerator: 'CmdOrCtrl+-', role: 'zoomOut' },
        { type: 'separator' },
        { label: '切换全屏', accelerator: 'F11', role: 'togglefullscreen' }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            // 可以显示关于对话框
          }
        }
      ]
    }
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

// 处理证书错误（如果需要）
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  // 开发环境下忽略证书错误
  if (isDev) {
    event.preventDefault()
    callback(true)
  } else {
    callback(false)
  }
})

